#pragma once

#include <vector>
#include "inetaddr.hpp"
#include "Thread.hpp"

using namespace ThreadModule;

class Route
{
public:
    bool IsExist(InetAddr &peer)
    {
        for (auto &user : _online_user)
        {
            if (user == peer)
                return true;
        }
        return false;
    }

    void AddUser(InetAddr &peer)
    {
        LOG(LogLevel::INFO) << "新增一个在线用户: " << peer.StringAddr();
        _online_user.push_back(peer);
    }

    void DeleteUser(InetAddr& peer)
    {
        for(auto it = _online_user.begin(); it != _online_user.end(); it++)
        {
            if (*it == peer)
            {
                LOG(LogLevel::INFO) << "删除一个在线用户: " << peer.StringAddr() << "成功";
                _online_user.erase(it);
                break;
            }
        }
    }

    void MessageRoute(int sockfd, std::string message, InetAddr &peer)
    {
        if (!IsExist(peer))
        {
            AddUser(peer);
        }

        std::string send_message = peer.StringAddr() + message;

        for (auto &user : _online_user)
        {
            int n = sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&(user.NetAddr()), sizeof(user.NetAddr()));
            (void)n;
        }

        if(message == "QUIT")
        {
            LOG(LogLevel::INFO) << "删除一个在线用户: " << peer.StringAddr();
            DeleteUser(peer);
        }
    }

private:
    std::vector<InetAddr> _online_user; // 在线用户
};